import React, { useMemo, useRef, useState } from "react";
import GridItem from "../GridItem";
import CenterItem from "../CenterItem";
import Popover from "components/Popover";
import { useGridContext } from "context/useGridContext";
import { addRoulette } from "api/backend";
import "./index.less";

export default function GridBox() {
  // 获取抽奖九宫格的Context
  const { gridList } = useGridContext();
  const dateRef = useRef();
  const [popVisible, setPopVisible] = useState(false);

  // 创建奖池前检测数据
  const addJackpot = () => {
    let flag = false,
      probNum = 0,
      releaseProbNum = 0;
    const currDate = new Date().getTime(),
      preDate = new Date(dateRef.current.value).getTime(),
      centerIndex = Math.floor(gridList.length / 2);
    if (currDate > preDate) return false;
    gridList.forEach((item, index) => {
      // 跳过中间
      if (index === centerIndex) return;
      if (!item.imgPath && !item.title) flag = true;
      probNum += parseFloat(item.prob);
      releaseProbNum += parseFloat(item.releaseProb);
    });
    // 奖池总概率要等于100
    if (probNum !== 100) return;
    if (releaseProbNum !== 100) return;
    // 看奖池数据有无错误，无错误可上传至服务器
    if (!flag) handleJackpot(centerIndex, preDate);
  };

  // 处理新建转盘所需数据
  const handleJackpot = (centerIndex, timeStamp) => {
    // 筛选出中间的格子
    const tmpGridList = gridList.filter((_, index) => index !== centerIndex);
    // 奖品id列表
    const prize_ids = tmpGridList.map((item) => parseInt(item.id));
    // 每个奖品的抽中概率
    const prize_probability = tmpGridList.map((item) => item.prob);
    // 每个奖品在开奖时的概率
    const release_prize_probability  = tmpGridList.map((item) => item.releaseProb);
    const data = {
      slot_num: gridList.length - 1,
      prize_ids,
      prize_probability,
      release_prize_at: timeStamp,
      release_prize_end_at: timeStamp,
      release_prize_probability,
      // picture_url,
    };
    uploadJackpot(data);
  };

  // 新建转盘
  const uploadJackpot = async (data) => {
    await addRoulette(data);
    setPopVisible(true);
  }

  // 弹出框隐藏
  const ensureHandle = () => {
    setPopVisible(false);
  }

  const centerIndex = useMemo(
    () => Math.floor(gridList.length / 2),
    [gridList]
  );
  return (
    <div className="grid-box-container">
      <div className="grid-box">
        {gridList.map((item, index) =>
          index === centerIndex ? (
            <CenterItem key={index} />
          ) : (
            <GridItem key={index} info={item} location={index} />
          )
        )}
      </div>
      <div className="grid-date-picker">
        <label htmlFor="date">
          大奖开奖时间:
          <input
            ref={dateRef}
            type="datetime-local"
            name="date"
          />
        </label>
      </div>
      <div className="grid-button">
        <button onClick={addJackpot}>创建奖池</button>
      </div>
      <Popover appear={popVisible} title="创建成功" ensureHandle={ensureHandle} />
    </div>
  );
}
